#!/bin/bash

# 🔥 支付宝SDK模拟器编译问题快速修复脚本
# 作用：修改tobias.podspec，让项目可以在iOS模拟器上编译运行

echo "=================================="
echo "🔥 支付宝SDK模拟器编译问题修复"
echo "=================================="
echo ""

# 查找tobias路径
TOBIAS_PATH=$(find ~/.pub-cache/hosted -name "tobias-*" -type d | head -n 1)

if [ -z "$TOBIAS_PATH" ]; then
  echo "❌ 未找到tobias插件"
  echo "请先运行: flutter pub get"
  exit 1
fi

PODSPEC_PATH="$TOBIAS_PATH/ios/tobias.podspec"

if [ ! -f "$PODSPEC_PATH" ]; then
  echo "❌ 未找到tobias.podspec文件"
  echo "路径: $PODSPEC_PATH"
  exit 1
fi

echo "✅ 找到tobias插件: $TOBIAS_PATH"
echo ""

# 备份原文件
BACKUP_PATH="${PODSPEC_PATH}.backup"
if [ ! -f "$BACKUP_PATH" ]; then
  echo "📦 备份原文件..."
  cp "$PODSPEC_PATH" "$BACKUP_PATH"
  echo "✅ 备份完成: $BACKUP_PATH"
else
  echo "ℹ️  备份文件已存在，跳过备份"
fi

echo ""
echo "🔧 开始修复..."

# 1. 修复 tobias.podspec
echo "📝 修复 tobias.podspec..."

if grep -q "# s.resource.*AlipaySDK/AlipaySDK.bundle" "$PODSPEC_PATH" && \
   grep -q "# s.vendored_frameworks.*AlipaySDK/AlipaySDK.framework" "$PODSPEC_PATH"; then
  echo "  ✅ tobias.podspec 已修复"
else
  # 注释掉AlipaySDK相关的配置
  sed -i '' 's/^  s\.resource.*AlipaySDK\/AlipaySDK\.bundle/#  s.resource              = '\''AlipaySDK\/AlipaySDK.bundle'\''/' "$PODSPEC_PATH"
  sed -i '' 's/^  s\.vendored_frameworks.*AlipaySDK\/AlipaySDK\.framework/#  s.vendored_frameworks   = '\''AlipaySDK\/AlipaySDK.framework'\''/' "$PODSPEC_PATH"
  
  # 添加注释说明
  sed -i '' '/^#  s\.resource.*AlipaySDK/i\
  # 🔥 支付宝SDK仅在真机时加载（模拟器不支持）
' "$PODSPEC_PATH"
  echo "  ✅ tobias.podspec 修复完成"
fi

# 2. 修复 TobiasPlugin.m
PLUGIN_M_PATH="$TOBIAS_PATH/ios/Classes/TobiasPlugin.m"
echo ""
echo "📝 修复 TobiasPlugin.m..."

if grep -q "TARGET_OS_SIMULATOR" "$PLUGIN_M_PATH"; then
  echo "  ✅ TobiasPlugin.m 已修复"
else
  # 备份
  cp "$PLUGIN_M_PATH" "${PLUGIN_M_PATH}.backup"
  
  # 修改头部导入（使用条件编译）
  sed -i '' 's/#import <AlipaySDK\/AlipaySDK\.h>/#if TARGET_OS_SIMULATOR\
#warning "AlipaySDK is not available on iOS Simulator. Alipay functions will return errors."\
#else\
#import <AlipaySDK\/AlipaySDK.h>\
#endif/g' "$PLUGIN_M_PATH"
  
  echo "  ✅ TobiasPlugin.m 修复完成"
  echo "  ℹ️  注意：TobiasPlugin.m 的其他方法需要手动添加条件编译"
fi

echo ""
echo "✅ 所有修复完成"
echo ""
echo "📋 后续步骤:"
echo "  1. cd ios && pod install"
echo "  2. flutter clean"
echo "  3. flutter run"
echo ""
echo "⚠️  注意事项:"
echo "  - 模拟器可以运行，但不支持支付宝支付功能"
echo "  - 真机测试支付功能时，需要恢复原文件"
echo "  - 恢复命令: cp $BACKUP_PATH $PODSPEC_PATH"
echo ""
echo "=================================="
echo "✅ 修复完成！"
echo "=================================="

